package com.taotao.job.core.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.taotao.job.core.enums.JobType;
import com.taotao.job.core.enums.StartType;
import com.taotao.job.core.executor.ExecutorContext;
import com.taotao.job.core.model.JobMeta;
import com.taotao.job.core.trigger.context.TriggerContext;
import com.taotao.job.core.trigger.context.TriggerFeature;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Map;

/**
 * @author fanbeibei
 * @version 1.0
 * @date 2021/2/22 15:01
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JobBussinessUtil {


    /**
     * 获取分片索引与执行器地址映射关系
     *
     * @param addressList
     * @param shardingCount
     * @return shardingIndex -> address
     */
    public static Map<Integer, String> getShardingExecutorAddressMap(List<String> addressList, int shardingCount) {
        Preconditions.checkArgument(null != addressList && addressList.size() > 0);
        Preconditions.checkArgument(shardingCount > 0);


        Map<Integer, String> map = Maps.newHashMapWithExpectedSize(shardingCount);
        //1. 用洗牌算法随机打乱addressList
        addressList = ShuffleCardUtil.shuffleCards(addressList);
        int len = addressList.size();
        //2. 均匀分配
        for (int i = 0; i < shardingCount; i++) {
            map.put(i, addressList.get(i % len));
        }

        return map;
    }


    public static long getCronShouldTriggerTime() {
        return -1;
    }


    public static long getRerunShouldTriggerTime() {
        return -1;
    }


    public static long getWorkflowNodeShouldTriggerTime() {
        return System.currentTimeMillis();
    }


    /**
     * 是否需要触发远程执行器
     *
     * @return
     */
    public static boolean isTriggerRemote() {
        return true;
    }


    public static void validExecutorContext(ExecutorContext executorContext) {
        Preconditions.checkArgument(null != executorContext);
        Preconditions.checkArgument(null != executorContext.getJobId(), " jobId is null ");
        Preconditions.checkArgument(null != executorContext.getJobInstanceId(), "jobInstanceId is null");
        Preconditions.checkArgument(null != JobType.getByCode(executorContext.getJobType()), "error JobType:" + executorContext.getJobType());
        Preconditions.checkArgument(null != StartType.getByCode(executorContext.getStartType()), "error StartType:" + executorContext.getStartType());
    }


}
